package plgutils

import (
	"sync"
	"time"
)

type VarFromURLItem struct {
	owner  *PlgUtilAppVars
	key    string
	url    string
	val    string
	lk     sync.RWMutex
	uptime time.Time
}

func NewVarFromURLItem(owner *PlgUtilAppVars) *VarFromURLItem {
	rval := &VarFromURLItem{owner: owner}
	return rval
}

func (this *VarFromURLItem) LogMsg(s string, args ...interface{}) {
	own := this.owner
	if own == nil {
		return
	}
	own.msglst.LogMsg(s, args...)
}

//func (this *VarFromURLItem) GetValue() (err error, rval string) {
//	respBuf, err := yhttp.HttpGet(this.url)
//	if err != nil {
//		this.LogMsg("[%s]获取数据异常:%s, url:%s", this.key, err.Error(), this.url)
//		return err, ""
//	}
//	if len(respBuf) == 0 {
//		//this.LogMsg("[%s]获取数据为空, url:%s", this.key, this.url)
//		return nil, ""
//	}
//	json, err := wrapper.NewSVFromBuf(respBuf)
//	if err != nil {
//		tmpstr := string(respBuf)
//		if tmpstr == "err" {
//			return fmt.Errorf("response err from server"), ""
//		}
//		return nil, tmpstr
//		//this.LogMsg("[%s]url:%s, val:%v", this.key, this.url, this.val)
//	} else {
//		if json.IntByName("code", 0) == 0 {
//			return nil, json.StringByName("val", "")
//		} else {
//			return fmt.Errorf("%s", json.StringByName("msg", "")), json.StringByName("val", "")
//		}
//	}
//}

func (this *VarFromURLItem) Reload() bool {
	this.lk.Lock()
	defer this.lk.Unlock()
	err, v0 := GetUrlVarRawValue(this.url)
	if err != nil {
		this.LogMsg("[%s]url:%s, load err:%s", this.key, this.url, err.Error())
		return false
	}
	if v0 != this.val {
		this.LogMsg("[%s]url:%s, value update:%s->%s", this.key, this.url, this.val, v0)
		this.val = v0
		this.uptime = time.Now()
	}

	return true
}
